package org.example.algorithm.linkedlist;

//1 2 3 4 5
public class ReverseKGroupSolution {

    public ListNode reverseKGroup(ListNode head, int k) {
        int len = getListLen(head);
        if (len < k) {
            return head;
        }
        ListNode cur = head;
        ListNode dummy = new ListNode();
        ListNode tail = dummy;
        for (int i=0;i<len/k;i++) {
            ListNode partHead = null;
            ListNode partTail = cur;
            for (int j=0;j<k;j++) {
                ListNode temp = cur.next;
                cur.next = partHead;
                partHead = cur;
                cur = temp;
            }
            tail.next = partHead;
            tail = partTail;
        }
        tail.next = cur;
        return dummy.next;
    }

    private int getListLen(ListNode head) {
        int len = 0;
        ListNode cur = head;
        while (cur != null) {
            len++;
            cur = cur.next;
        }
        return len;
    }
}
